<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>文件上传</title>
	</head>
	<script src="//cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
	<body>
		<input type="file" name="" id="btnFile" value="" />
		<input type="button" name="" id="" value="上传" onclick="uploadFile()" />
		<p><progress id="progress" value="0" max="100"></p>
	</body>
	<script type="text/javascript">
		let btnFile = document.querySelector('#btnFile');
		let progressOk = document.querySelector('#progress')

		let config = {
			headers: {
				'Content-Type': 'multipart/form-data',
			},
			transformRequest: [function(data) {
				return data
			}],
			onUploadProgress: progressEvent => {
				let persent = (progressEvent.loaded / progressEvent.total * 100 | 0) //上传进度百分比
				console.log(persent)
			},
		}

		function uploadFile() {
			let file = btnFile.files[0];
			let formData = new FormData();
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data',
				},
				transformRequest: [function(data) {
					return data
				}],
				onUploadProgress: progressEvent => {
					console.log(progressEvent)
					let persent = (progressEvent.loaded / progressEvent.total * 100 | 0) //上传进度百分比
					console.log(persent)
					// 渲染进度条
					progressOk.value = persent
				},
			}

			formData.append('file', file);
			axios.post('http://127.0.0.1:3000/upload',
				formData, config
			).then(function(res) {
				console.log(res)

			}).catch(function(Error) {
				console.log("err:"+Error)
				return Error
			}).finally(function(res){
				console.log('执行完成')
			})


		}
	</script>
</html>
